<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        class="filter-item"
        style="margin-left: 10px;margin-bottom: 20px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加版本</el-button>
      <el-button>删除版本</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="loading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="序号" prod="id" align="center" width="60">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="小版本号" prod="versionCode" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.versionCode }}</span>
        </template>
      </el-table-column>

      <el-table-column label="大版本号" prod="versisonName" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.versionName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="版本描述" prop="versionDesc" align="center" width="120">
        <template slot-scope="{row}">
          <span>{{ row.versionDesc }}</span>
        </template>
      </el-table-column>

      <el-table-column label="下载链接" prop="fileUrl" align="center" width="180">
        <template slot-scope="{row}">
          <span>{{ row.fileUrl }}</span>
        </template>
      </el-table-column>

      <el-table-column label="文件大小(KB)" prod="fileSize" align="center" width="110">
        <template slot-scope="{row}">
          <span>{{ row.fileSize }}</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" prod="status" align="center" width="80">
        <template slot-scope="{row}">
          <span v-if="row.status==0">使用中</span>
          <span v-else>已禁用</span>
        </template>
      </el-table-column>

      <el-table-column label="更新类型" prod="type" align="center" width="80">
        <template slot-scope="{row}">
          <span v-if="row.type==1">强制更新</span>
          <span v-else>普通更新</span>
        </template>
      </el-table-column>

      <el-table-column label="更新时间" prod="updateTime" align="center" width="160">
        <template slot-scope="{row}">
          <span>{{ row.updateTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" prod="createTime" align="center" width="160">
        <template slot-scope="{row}">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="240" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
          <el-button v-if="row.status!=1" type="info" size="mini" @click="handleForbidden(row)">禁用</el-button>
          <el-button v-else type="info" size="mini" @click="handleEnable(row)">启用</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item>
          <el-upload
            ref="upload"
            action="file/upload"
            name="file"
            :multiple="false"
            :show-file-list="true"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :file-list="fileList"
            :auto-upload="false"
            :accept="'file/*'"
          >
            <el-button slot="trigger" size="medium" type="primary">选取文件</el-button>
            <el-button
              style="margin-left: 10px;"
              size="medium"
              type="success"
              @click="submitUpload"
            >上传到服务器</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="文件路径">
          <el-input v-model="temp.fileUrl" :disabled="false" />
        </el-form-item>

        <el-form-item label="文件大小(KB)">
          <el-input v-model="temp.fileSize" placeholder="单位KB" :disabled="false" />
        </el-form-item>

        <el-form-item label="小版本号">
          <el-input v-model="temp.versionCode" />
        </el-form-item>

        <el-form-item label="大版本号">
          <el-input v-model="temp.versionName" placeholder />
        </el-form-item>

        <el-form-item label="状态">
          <el-input v-model="temp.status" />
        </el-form-item>

        <el-form-item label="更新类型">
          <el-select v-model="this.options[0].label" placeholder="请选择更新类型" @change="onSelectChange">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="版本描述">
          <el-input v-model="temp.versionDesc" type="textarea" placeholder="APP版本更新描述" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
    <el-pagination
      class="paginations"
      background
      layout="total, prev, pager, next"
      prev-text=" &nbsp; &nbsp; 上一页 &nbsp; &nbsp; "
      next-text="&nbsp; &nbsp; 上一页&nbsp; &nbsp;  "
      :page-size="pageSize"
      :total="total"
      @current-change="onCurrentChange"
    />
  </div>
</template>

<script>
import {
  createVersion,
  fetchList,
  forbiddenVersion,
  deleteVersion,
  invokeVersion
} from '@/api/versions'

export default {
  name: 'Version',
  data() {
    return {
      tableKey: 0,
      loading: true,
      list: null,
      dialogFormVisible: false,
      dialogStatus: '',
      temp: {
        id: undefined,
        versionCode: '',
        versionName: '',
        versionDesc: '',
        fileUrl: '',
        fileSize: 0,
        type: 1,
        status: 1
      },
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {},
      fileList: [],

      options: [
        {
          value: '0',
          label: '普通更新'
        },
        {
          value: '1',
          label: '强制更新'
        }
      ],
      total: 50,
      pageNum: 1,
      pageSize: 3
    }
  },

  mounted() {
    this.getList()
  },
  methods: {
    // 请求列表数据
    getList() {
      const data = {
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }
      this.loading = true
      fetchList(data).then((response) => {
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.loading = false
        }, 500)
      })
    },

    onCurrentChange(val) {
      this.pageNum = val
      this.getList()
    },

    // 上传文件成功
    handleUploadSuccess(response, file, fileList) {
      this.temp.fileUrl = response.data
      this.temp.fileSize = (file.size / 1024).toFixed(2)
    },
    // 上传文件失败
    handleUploadError(err, file, fileList) {
      this.$message({
        type: 'error',
        message: err
      })
    },
    // 选择普通更新还是强制更新监听
    onSelectChange(val) {
      this.temp.type = val
    },

    handleCreate() {
      this.resetTemp()
      this.dialogFormVisible = true
      this.dialogStatus = 'create'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createVersion(this.temp).then((res) => {
            if (res.code === 0) {
              this.dialogFormVisible = false
              this.$message({
                type: 'success',
                message: '添加成功'
              })
              this.getList()
              // 重置文件列表
              this.fileList = []
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
          })
        }
      })
    },
    // 更新操作
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogFormVisible = true
      this.dialogStatus = 'update'
      this.temp.id = row.id
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.createData()
        }
      })
    },

    // 启用操作
    handleEnable(row) {
      const data = {
        id: row.id
      }
      this.$confirm('此操作将启用这个版本，是否继续?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.enableData(data)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消启用'
          })
        })
    },
    enableData(param) {
      invokeVersion(param).then((res) => {
        if (res.code === 0) {
          this.getList()
          this.$message({
            type: 'success',
            message: '操作成功'
          })
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },

    // 禁用操作
    handleForbidden(row) {
      const data = {
        id: row.id
      }
      this.$confirm('此操作将会禁用这个版本，是否继续?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.forbiddenData(data)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消禁用'
          })
        })
    },

    forbiddenData(param) {
      forbiddenVersion(param).then((res) => {
        if (res.code === 0) {
          this.getList()
          this.$message({
            type: 'info',
            message: '禁用成功'
          })
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },

    // 删除操作
    handleDelete(row) {
      const data = {
        id: row.id
      }
      this.$confirm('此操作将会删除这条记录，是否继续?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteData(data)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    deleteData(param) {
      deleteVersion(param).then((res) => {
        if (res.code === 0) {
          this.getList()
          this.$message({
            type: 'success',
            message: '删除成功'
          })
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },

    resetTemp() {
      this.temp = {
        id: undefined,
        versionCode: '',
        versionName: '',
        versionDesc: '',
        fileUrl: '',
        fileSize: 0,
        type: 0,
        status: 0
      }
    },
    submitUpload() {
      // 上传文件
      this.$refs.upload.submit()
    }
  }
}
</script>

<style lang="scss">
.app-container {
  position: relative;
}

.paginations {
  position: absolute;
  bottom: -50px;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
